package com.gulimall.seckill.Interceptor;

import com.common.constant.LoginConstant;
import com.common.to.MemberTo;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Rookie-6688
 * @Description 购物车拦截方法，用于在查看购物车之前匹配对应的 user-key Cookie，从而返回匹配的购物车数据
 * @Create 2021-04-25 16:18
 */
public class SeckillInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<MemberTo> userMap = new ThreadLocal<>();

    /**
     * 在进入秒杀业务前，先进行登陆验证
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 防止在消息队列解锁库存时发送的order远程调用没有携带用户被拦截，所以这里放行（消息队列本身就不携带用户消息的Cookie，所以这里向ware发送的feign线程请求里塞Cookie还是不行）
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/kill", uri);
        if(!match){
            return true;
        }

        MemberTo memberTo = (MemberTo) request.getSession().getAttribute(LoginConstant.LOGIN_USERNAME);
        if(memberTo == null){
            request.getSession().setAttribute("msg","请先登陆");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }else{
            userMap.set(memberTo);
            return true;
        }
    }

}
